package com.example.controller;

import com.example.entity.Course;
import com.example.entity.bo.StudentCourseResultBO;
import com.example.entity.example.CourseExample;
import com.example.service.CourseService;
import com.example.service.StudentService;
import com.example.service.UserService;
import com.example.util.CustomConstant;
import com.example.util.ResultEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/course")
public class CourseController {
    @Autowired
    CourseService courseService;

    @Autowired
    UserService userService;

    @Autowired
    StudentService studentService;

    @ResponseBody
    @RequestMapping("/get.json")
    public ResultEntity<List<Course>> get(@RequestParam("page") Integer page,
                                          @RequestParam("limit") Integer limit,
                                          @RequestParam(value = "id", required = false) String id,
                                          @RequestParam(value = "name", required = false) String name,
                                          @RequestParam(value = "category", required = false) String category,
                                          @RequestParam(value = "examination", required = false) String examination,
                                          @RequestParam(value = "credit", required = false) Integer credit
    ) {
        CourseExample example = new CourseExample();
        CourseExample.Criteria criteria = example.createCriteria();
        if (id != null) {
            id = '%' + id + '%';
            criteria.andIdLike(id);
        }
        if (name != null && !name.isEmpty()) {
            name = '%' + name + '%';
            criteria.andNameLike(name);
        }
        if (category != null && !category.isEmpty()) {
            criteria.andCategoryEqualTo(category);
        }
        if (examination != null && !examination.isEmpty()) {
            criteria.andExaminationEqualTo(examination);
        }
        if (credit != null) {
            criteria.andCreditEqualTo(credit);
        }
        List<Course> courses = courseService.getByExampleWithLimit(example, page, limit);
        long count = courseService.getCountByExample(example);
        return ResultEntity.createResultEntity(0, null, count, courses);
    }

    @PreAuthorize("hasRole('ROLE_管理员')")
    @RequestMapping("/add/page.html")
    public String addPage() {
        return "course/course-add";
    }

    @PreAuthorize("hasRole('ROLE_管理员')")
    @ResponseBody
    @RequestMapping("/add")
    public ResultEntity<Object> add(@RequestBody Course course) {
        courseService.add(course);
        return ResultEntity.successWithoutData();
    }

    @PreAuthorize("hasRole('ROLE_管理员')")
    @RequestMapping("/{id}/modify/page.html")
    public String modifyPage(ModelMap modelMap, @PathVariable("id") String id) {
        Course course = courseService.getById(id);
        modelMap.addAttribute("course", course);
        return "course/course-modify";
    }

    @PreAuthorize("hasRole('ROLE_管理员')")
    @ResponseBody
    @RequestMapping("/update")
    public ResultEntity<Object> update(@RequestBody Course course) {
        courseService.updateById(course);
        return ResultEntity.successWithoutData();
    }

    @PreAuthorize("hasRole('ROLE_管理员')")
    @ResponseBody
    @RequestMapping("/remove")
    public ResultEntity<Object> remove(@RequestParam("id") String id) {
        courseService.removeById(id);
        return ResultEntity.successWithoutData();
    }

    @PreAuthorize("hasRole('ROLE_管理员') or hasRole('ROLE_学生')")
    @ResponseBody
    @RequestMapping("/selection")
    public ResultEntity<Object> selection(@RequestParam("courseId") String courseId,
                                          @RequestParam("userId") Integer userId) {
        String studentId = userService.getStudentId(userId);
        if (studentId == null) {
            return ResultEntity.failedWithoutData(CustomConstant.MESSAGE_ACCESS_DENIED);
        }
        if (studentService.getStudentCourseResultsByIdAndCourseId(studentId, courseId) != null) {
            return ResultEntity.failedWithoutData(CustomConstant.MESSAGE_THE_COURSE_ALREADY_SELECT);
        }
        courseService.selection(courseId, studentId);
        return ResultEntity.successWithoutData();
    }

    @PreAuthorize("hasRole('ROLE_管理员') or hasRole('ROLE_学生')")
    @ResponseBody
    @RequestMapping("/unSelection")
    public ResultEntity<Object> unSelection(@RequestParam("courseId") String courseId,
                                            @RequestParam("userId") Integer userId) {
        String studentId = userService.getStudentId(userId);
        if (studentId == null) {
            return ResultEntity.failedWithoutData(CustomConstant.MESSAGE_ACCESS_DENIED);
        }
        StudentCourseResultBO courseResult = studentService.getStudentCourseResultsByIdAndCourseId(studentId, courseId);
        if (courseResult == null) {
            // 课程不存在
            return ResultEntity.failedWithoutData(CustomConstant.MESSAGE_THE_COURSE_IS_NOT_SELECT);
        }
        if (courseResult.getScore() != null) {
            // 已出成绩的课程不能退选
            return ResultEntity.failedWithoutData(CustomConstant.MESSAGE_THE_COURSE_ALREADY_HAVE_SCORE);
        }
        courseService.unSelection(courseId, studentId);
        return ResultEntity.successWithoutData();
    }
}
